<template>
  <div class="game-page-container">
    <!-- 左侧玩家列表 -->
    <div class="players-sidebar">
      <div class="players-sidebar-header">
        <h3>玩家列表</h3>
        <span class="player-count">{{ room?.players?.length || 0 }}人</span>
      </div>
      <div class="players-sidebar-list">
        <div
          v-for="player in room?.players"
          :key="player.id"
          class="sidebar-player-item"
          :class="{ 
            leader: player.isLeader || player.id === currentLeaderId,
            inTeam: room?.selectedTeam?.includes(player.id),
            currentPlayer: player.id === (room?.currentPlayerId || socket.value?.id)
          }"
        >
          <div class="sidebar-player-avatar">
            <span v-if="player.isLeader || player.id === currentLeaderId" class="leader-icon">👑</span>
            <span v-else class="player-number">{{ getPlayerNumber(player.id) }}</span>
          </div>
          <div class="sidebar-player-name">{{ player.name }}</div>
          <div class="sidebar-player-badges">
            <span v-if="player.isLeader || player.id === currentLeaderId" class="badge leader-badge">队长</span>
            <span v-if="room?.selectedTeam?.includes(player.id)" class="badge team-badge">任务</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧游戏内容 -->
    <div class="game-content">
      <h2>游戏进行中</h2>

      <!-- 我的身份卡 -->
      <div class="my-role-card" :class="getRoleClass(roleInfo?.role)">
        <div class="role-card-header">
          <div class="role-icon-large">{{ getRoleInfo(roleInfo?.role)?.icon || '👤' }}</div>
          <h3>您的身份: {{ roleInfo?.role }}</h3>
        </div>
        <div class="role-card-body" v-if="roleInfo && getRoleInfo(roleInfo.role)">
          <div class="role-description">
            <p class="role-desc-text">{{ getRoleInfo(roleInfo.role).description }}</p>
          </div>
          <div class="role-ability">
            <strong>特殊能力：</strong>
            {{ getRoleInfo(roleInfo.role).ability }}
          </div>
          <div class="role-tips">
            <strong>提示：</strong>
            {{ getRoleInfo(roleInfo.role).tips }}
          </div>
        </div>
        <div v-if="roleInfo" style="margin-top: 15px; padding-top: 15px; border-top: 2px solid #e0e0e0;">
          <div v-if="roleInfo.role === '梅林' && roleInfo.evilPlayers">
            <p>
              <strong>坏人（除莫德雷德外）:</strong>
            </p>
            <ul style="margin-top: 10px;">
              <li v-for="evil in roleInfo.evilPlayers" :key="evil.id" style="margin: 5px 0;">{{ room?.players.find(p => p.id === evil.id)?.name }} - {{ evil.role }}</li>
            </ul>
          </div>
          <div v-else-if="roleInfo.role === '派西维尔'">
            <p>
              <strong>梅林和莫德雷德中有一个人，请仔细判断！</strong>
            </p>
          </div>
          <div v-else-if="['莫德雷德', '刺客', '爪牙'].includes(roleInfo.role) && roleInfo.evilPlayers">
            <p>
              <strong>其他坏人:</strong>
            </p>
            <ul style="margin-top: 10px;">
              <li v-for="evil in roleInfo.evilPlayers" :key="evil.id" style="margin: 5px 0;">{{ room?.players.find(p => p.id === evil.id)?.name }} - {{ evil.role }}</li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 游戏状态信息 -->
      <div class="game-status">
        <h3>任务 {{ (room?.currentQuest || 0) + 1 }} / 5</h3>
        <div class="quest-progress">
          <div v-for="(result, index) in room?.questResults" :key="index" class="quest-result" :class="result ? 'success' : 'fail'">
            <span>{{ index + 1 }}</span>
          </div>
          <div v-for="n in (5 - (room?.questResults?.length || 0))" :key="'pending-' + n" class="quest-result pending">
            <span>{{ (room?.questResults?.length || 0) + n }}</span>
          </div>
        </div>
      </div>

      <!-- 队长选择任务队伍 -->
      <div v-if="room?.phase === 'selectLeader' || room?.phase === 'selectTeam'" class="game-phase">
        <div v-if="isCurrentLeader" class="leader-action">
          <div class="leader-header">
            <h3>👑 您是当前队长</h3>
            <div class="leader-info">
              <p class="quest-info">
                任务 {{ (room?.currentQuest || 0) + 1 }} 需要
                <strong>{{ requiredTeamSize }}</strong> 人
              </p>
              <p class="selection-progress">
                已选择:
                <span class="progress-text">{{ selectedTeam.length }}</span> /
                <span class="progress-total">{{ requiredTeamSize }}</span>
              </p>
            </div>
          </div>

          <div class="team-selection-container">
            <div v-if="selectedTeam.length > 0" class="selected-preview">
              <h4>已选择的队伍：</h4>
              <div class="selected-players">
                <div v-for="playerId in selectedTeam" :key="playerId" class="selected-player-item">
                  <span class="player-avatar-small">✓</span>
                  <span>{{ getPlayerName(playerId) }}</span>
                </div>
              </div>
            </div>

            <button @click="openTeamSelectModal" class="select-team-btn">
              <span v-if="selectedTeam.length > 0">✏️ 修改队伍</span>
              <span v-else>➕ 选择任务队伍</span>
            </button>
          </div>

          <div class="action-buttons">
            <button
              v-if="room?.phase === 'selectLeader'"
              @click="handleConfirmTeam"
              :disabled="selectedTeam.length !== requiredTeamSize"
              class="confirm-btn"
              :class="{ 'btn-ready': selectedTeam.length === requiredTeamSize }"
            >
              <span v-if="selectedTeam.length === requiredTeamSize">✓ 确认队伍</span>
              <span v-else>还需选择 {{ requiredTeamSize - selectedTeam.length }} 人</span>
            </button>
          </div>
        </div>
        <div v-else class="waiting">
          <h3>等待队长选择任务队伍</h3>
          <p>当前队长: {{ currentLeaderName }}</p>
          <div v-if="room?.phase === 'selectTeam' && room?.selectedTeam?.length > 0" class="selected-team-preview">
            <p>
              <strong>队长已选择队伍：</strong>
            </p>
            <div class="team-members">
              <span v-for="playerId in room?.selectedTeam" :key="playerId" class="team-member">{{ getPlayerName(playerId) }}</span>
            </div>
            <p class="waiting-hint">等待投票开始...</p>
          </div>
        </div>
      </div>

      <!-- 选择队伍弹窗 -->
      <div v-if="showTeamSelectModal" class="modal-overlay" @click.self="closeTeamSelectModal">
        <div class="modal-content team-select-modal">
          <div class="modal-header">
            <h3>选择任务队伍</h3>
            <button class="modal-close" @click="closeTeamSelectModal">×</button>
          </div>
          <div class="modal-body">
            <div class="modal-info">
              <p class="quest-info">
                任务 {{ (room?.currentQuest || 0) + 1 }} 需要选择
                <strong>{{ requiredTeamSize }}</strong> 人
              </p>
              <p class="selection-progress">
                已选择:
                <span class="progress-text">{{ selectedTeam.length }}</span> /
                <span class="progress-total">{{ requiredTeamSize }}</span>
              </p>
            </div>
            <div class="modal-player-list">
              <div
                v-for="player in room?.players"
                :key="player.id"
                class="modal-player-item"
                :class="{ 
                selected: selectedTeam.includes(player.id),
                disabled: !selectedTeam.includes(player.id) && selectedTeam.length >= requiredTeamSize
              }"
              >
                <label class="player-checkbox-label">
                  <input
                    type="checkbox"
                    :checked="selectedTeam.includes(player.id)"
                    :disabled="!selectedTeam.includes(player.id) && selectedTeam.length >= requiredTeamSize"
                    @change="togglePlayerSelection(player.id)"
                    class="player-checkbox"
                  />
                  <div class="player-info">
                    <div class="player-avatar-modal">
                      <span v-if="selectedTeam.includes(player.id)" class="check-icon">✓</span>
                      <span v-else class="player-number">{{ getPlayerNumber(player.id) }}</span>
                    </div>
                    <span class="player-name">{{ player.name }}</span>
                  </div>
                </label>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button @click="closeTeamSelectModal" class="modal-cancel-btn">取消</button>
            <button
              @click="confirmAndCloseModal"
              :disabled="selectedTeam.length !== requiredTeamSize"
              class="modal-confirm-btn"
              :class="{ 'btn-ready': selectedTeam.length === requiredTeamSize }"
            >确认 ({{ selectedTeam.length }}/{{ requiredTeamSize }})</button>
          </div>
        </div>
      </div>

      <!-- 投票表决任务队伍 -->
      <div v-if="room?.phase === 'voteTeam'" class="game-phase">
        <h3>投票表决任务队伍</h3>
        <div class="selected-team">
          <p>
            <strong>队长选择的任务队伍：</strong>
          </p>
          <div class="team-members">
            <span v-for="playerId in room?.selectedTeam" :key="playerId" class="team-member">{{ getPlayerName(playerId) }}</span>
          </div>
        </div>
        <div v-if="!room?.hasVoted" class="vote-buttons">
          <button @click="voteTeam(true)" class="vote-btn approve">✅ 同意</button>
          <button @click="voteTeam(false)" class="vote-btn reject">❌ 拒绝</button>
        </div>
        <div v-else class="voted">
          <p>✅ 您已投票，等待其他玩家...</p>
          <p>已投票: {{ room?.votesCount || 0 }} / {{ room?.totalPlayers || 0 }}</p>
        </div>
      </div>

      <!-- 刺杀阶段 -->
      <div v-if="room?.phase === 'assassination'" class="game-phase assassination-phase">
        <h3>🗡️ 刺杀阶段</h3>
        <div v-if="isAssassin" class="assassination-action">
          <div class="assassination-header">
            <h4>您是刺客，请选择要刺杀的玩家（梅林）</h4>
            <p class="assassination-hint">好人完成了3次任务！如果您猜对了梅林，坏人将获胜！</p>
          </div>
          <div class="player-selection-list">
            <div
              v-for="player in room?.players"
              :key="player.id"
              class="player-selection-item"
              :class="{ selected: selectedAssassinationTarget === player.id }"
              @click="selectAssassinationTarget(player.id)"
            >
              <span class="player-name">{{ player.name }}</span>
              <span v-if="selectedAssassinationTarget === player.id" class="selected-icon">✓</span>
            </div>
          </div>
          <div v-if="selectedAssassinationTarget" class="assassination-confirm">
            <button @click="confirmAssassination" class="assassination-btn">确认刺杀</button>
          </div>
        </div>
        <div v-else class="assassination-waiting">
          <p>等待刺客选择刺杀目标...</p>
          <p class="assassination-info">好人完成了3次任务！刺客正在秘密选择梅林...</p>
        </div>
      </div>

      <!-- 任务投票（成功/失败） -->
      <div v-if="room?.phase === 'voteQuest'" class="game-phase">
        <h3>任务执行中</h3>
        <div class="selected-team">
          <p>
            <strong>执行任务的队伍：</strong>
          </p>
          <div class="team-members">
            <span v-for="playerId in room?.selectedTeam" :key="playerId" class="team-member">{{ getPlayerName(playerId) }}</span>
          </div>
        </div>
        <div v-if="isInTeam && room?.questVotesCount < room?.teamSize" class="quest-vote-buttons">
          <p>请选择任务结果：</p>
          <button @click="voteQuest(true)" class="quest-vote-btn success">成功</button>
          <button @click="voteQuest(false)" class="quest-vote-btn fail">失败</button>
        </div>
        <div v-else-if="isInTeam" class="voted">
          <p>您已投票，等待其他任务队员...</p>
          <p>已投票: {{ room?.questVotesCount || 0 }} / {{ room?.teamSize || 0 }}</p>
        </div>
        <div v-else class="waiting">
          <p>等待任务队员投票...</p>
          <p>已投票: {{ room?.questVotesCount || 0 }} / {{ room?.teamSize || 0 }}</p>
        </div>
      </div>

      <!-- 任务结果 -->
      <div v-if="lastQuestResult !== null" class="quest-result-display">
        <h3>任务 {{ (room?.currentQuest || 0) }} 结果</h3>
        <div :class="lastQuestResult ? 'success-msg' : 'fail-msg'">{{ lastQuestResult ? '✅ 任务成功' : '❌ 任务失败' }}</div>
        <p v-if="lastQuestFailCount > 0">失败票数: {{ lastQuestFailCount }}</p>
      </div>

      <!-- 投票结果统计 -->
      <!-- 队伍投票结果 -->
      <div v-if="teamVoteResult" class="vote-result-statistics team-vote-result">
        <h3>📊 队伍投票结果</h3>
        <div class="vote-summary">
          <div class="vote-summary-item" :class="teamVoteResult.approved ? 'approved' : 'rejected'">
            <span class="vote-result-icon">{{ teamVoteResult.approved ? '✅' : '❌' }}</span>
            <span class="vote-result-text">{{ teamVoteResult.approved ? '通过' : '拒绝' }}</span>
            <span class="vote-count">{{ teamVoteResult.approveCount }} 同意 / {{ teamVoteResult.rejectCount }} 拒绝</span>
          </div>
        </div>
        <div class="vote-details">
          <h4>详细投票：</h4>
          <div class="vote-list">
            <div v-for="vote in teamVoteResult.voteDetails" :key="vote.playerId" class="vote-item" :class="vote.vote === true ? 'approve' : vote.vote === false ? 'reject' : 'pending'">
              <span class="player-name">{{ vote.playerName }}</span>
              <span class="vote-icon">
                <span v-if="vote.vote === true">✅ 同意</span>
                <span v-else-if="vote.vote === false">❌ 拒绝</span>
                <span v-else>⏳ 未投票</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 发车投票结果 -->
      <div v-if="launchVoteResult" class="vote-result-statistics launch-vote-result">
        <h3>🚀 发车投票结果</h3>
        <div class="vote-summary">
          <div class="vote-summary-item" :class="launchVoteResult.launched ? 'approved' : 'rejected'">
            <span class="vote-result-icon">{{ launchVoteResult.launched ? '✅' : '❌' }}</span>
            <span class="vote-result-text">{{ launchVoteResult.launched ? '通过' : '拒绝' }}</span>
            <span class="vote-count">{{ launchVoteResult.launchCount }} 发车 / {{ launchVoteResult.notLaunchCount }} 不发车</span>
          </div>
        </div>
        <div class="vote-details">
          <h4>详细投票：</h4>
          <div class="vote-list">
            <div v-for="vote in launchVoteResult.voteDetails" :key="vote.playerId" class="vote-item" :class="vote.vote === true ? 'approve' : vote.vote === false ? 'reject' : 'pending'">
              <span class="player-name">{{ vote.playerName }}</span>
              <span class="vote-icon">
                <span v-if="vote.vote === true">🚀 发车</span>
                <span v-else-if="vote.vote === false">⛔ 不发车</span>
                <span v-else>⏳ 未投票</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 任务投票结果 -->
      <div v-if="questVoteResult" class="vote-result-statistics quest-vote-result">
        <h3>⚔️ 任务投票结果</h3>
        <div class="vote-summary">
          <div class="vote-summary-item" :class="questVoteResult.success ? 'approved' : 'rejected'">
            <span class="vote-result-icon">{{ questVoteResult.success ? '✅' : '❌' }}</span>
            <span class="vote-result-text">{{ questVoteResult.success ? '任务成功' : '任务失败' }}</span>
            <span class="vote-count">{{ questVoteResult.successCount }} 成功 / {{ questVoteResult.failCount }} 失败</span>
          </div>
        </div>
        <div class="vote-details">
          <h4>详细投票：</h4>
          <div class="vote-list">
            <div v-for="vote in questVoteResult.voteDetails" :key="vote.playerId" class="vote-item" :class="vote.vote === true ? 'approve' : vote.vote === false ? 'reject' : 'pending'">
              <span class="player-name">{{ vote.playerName }}</span>
              <span class="vote-icon">
                <span v-if="vote.vote === true">✅ 成功</span>
                <span v-else-if="vote.vote === false">❌ 失败</span>
                <span v-else>⏳ 未投票</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 游戏结束界面 -->
      <div v-if="gameFinished" class="game-finished-overlay">
        <div class="game-finished-content">
          <div class="game-finished-header" :class="gameFinished.winner === 'good' ? 'good-win' : 'evil-win'">
            <h1 class="game-finished-title">{{ gameFinished.winner === 'good' ? '🎉 好人胜利！' : '💀 坏人胜利！' }}</h1>
            <p class="game-finished-subtitle">{{ gameFinished.winner === 'good' ? '正义战胜了邪恶！' : '邪恶势力获得了胜利！' }}</p>
          </div>

          <div class="game-finished-stats">
            <h3>任务结果统计</h3>
            <div class="quest-results-summary">
              <div class="quest-result-item">
                <span class="stat-label">成功任务：</span>
                <span class="stat-value success">{{ gameFinished.successCount }} / 5</span>
              </div>
              <div class="quest-result-item">
                <span class="stat-label">失败任务：</span>
                <span class="stat-value fail">{{ gameFinished.failCount }} / 5</span>
              </div>
            </div>
            <div class="quest-results-detail">
              <div v-for="(result, index) in gameFinished.questResults" :key="index" class="quest-result-badge" :class="result ? 'success' : 'fail'">任务 {{ index + 1 }}: {{ result ? '✅ 成功' : '❌ 失败' }}</div>
            </div>
          </div>

          <!-- 刺杀结果 -->
          <div v-if="gameFinished.assassination" class="game-finished-assassination">
            <h3>🗡️ 刺杀结果</h3>
            <div class="assassination-result" :class="gameFinished.assassination.isCorrect ? 'assassination-success' : 'assassination-fail'">
              <div class="assassination-info">
                <p>
                  <strong>刺客选择的目标：</strong>
                  {{ gameFinished.assassination.targetPlayerName }}
                </p>
                <p>
                  <strong>真正的梅林：</strong>
                  {{ gameFinished.assassination.merlinName }}
                </p>
                <p class="assassination-outcome">
                  <span v-if="gameFinished.assassination.isCorrect">✅ 刺客猜对了！刺杀了梅林，坏人获胜！</span>
                  <span v-else>❌ 刺客猜错了！梅林存活，好人获胜！</span>
                </p>
              </div>
            </div>
          </div>

          <div class="game-finished-players">
            <h3>所有玩家身份</h3>
            <div class="players-list">
              <div v-for="player in gameFinished.players" :key="player.id" class="player-role-item" :class="isGoodRole(player.role) ? 'good' : 'evil'">
                <span class="player-name">{{ player.name }}</span>
                <span class="player-role">{{ player.role }}</span>
                <span class="player-side">{{ isGoodRole(player.role) ? '好人阵营' : '坏人阵营' }}</span>
              </div>
            </div>
          </div>

          <div class="game-finished-actions">
            <!-- 房主显示：返回首页 和 进行下局游戏 -->
            <template v-if="isHost">
              <button @click="backToHome" class="back-btn">返回首页</button>
              <button @click="startNewGame" class="new-game-btn">进行下局游戏</button>
            </template>
            <!-- 非房主显示：返回房间 -->
            <template v-else>
              <button @click="backToRoom" class="back-btn">返回房间</button>
            </template>
          </div>
        </div>
      </div>

      <div v-if="error" class="error">{{ error }}</div>
      <div v-if="success" class="success">{{ success }}</div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useSocket } from "../composables/useSocket.js";
import { getRoleInfo, getPlayerCountConfig } from "../roles.js";

export default {
  name: "GamePage",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const { socket, connect, disconnect } = useSocket();

    const room = ref(null);
    const roleInfo = ref(null);
    const selectedTeam = ref([]);
    const showTeamSelectModal = ref(false);
    const selectedAssassinationTarget = ref(null);
    const error = ref("");
    const success = ref("");
    const lastQuestResult = ref(null);
    const lastQuestFailCount = ref(0);

    // 投票结果统计
    const teamVoteResult = ref(null);
    const launchVoteResult = ref(null);
    const questVoteResult = ref(null);

    // 游戏结束状态
    const gameFinished = ref(null);

    // 判断是否是房主
    const isHost = computed(() => {
      if (!room.value || !socket.value) return false;
      const currentPlayerId = room.value.currentPlayerId || socket.value.id;
      return room.value.host === currentPlayerId;
    });

    const isCurrentLeader = computed(() => {
      if (!room.value) {
        console.log("🔍 [队长识别] room.value 不存在");
        return false;
      }

      // 优先使用 room 中的 currentPlayerId（后端返回的）
      const currentPlayerId = room.value.currentPlayerId || socket.value?.id;

      if (!currentPlayerId) {
        console.warn("⚠️ [队长识别] 当前玩家ID不存在", {
          roomCurrentPlayerId: room.value.currentPlayerId,
          socketId: socket.value?.id,
          socketConnected: socket.value?.connected,
        });
        return false;
      }

      const leaderId = currentLeaderId.value;
      if (!leaderId) {
        console.warn("⚠️ [队长识别] 队长ID不存在");
        return false;
      }

      const isLeader = leaderId === currentPlayerId;

      // 详细的调试日志
      console.log("🔍 [队长识别] 身份检查:", {
        isLeader,
        leaderId,
        currentPlayerId,
        match: leaderId === currentPlayerId,
        roomPhase: room.value.phase,
        roomCurrentPlayerId: room.value.currentPlayerId,
        socketId: socket.value?.id,
      });

      if (isLeader) {
        console.log("✅ [队长识别] 您是队长！", { leaderId, currentPlayerId });
      } else {
        console.log("❌ [队长识别] 您不是队长", {
          队长ID: leaderId,
          您的ID: currentPlayerId,
        });
      }

      return isLeader;
    });

    const currentLeaderId = computed(() => {
      // 优先使用后端直接返回的 currentLeaderId
      if (room.value?.currentLeaderId) {
        return room.value.currentLeaderId;
      }
      // 降级方案：使用 leaderIndex 计算
      if (!room.value || !room.value.players) return null;
      const players = room.value.players;
      if (
        players.length === 0 ||
        room.value.leaderIndex === undefined ||
        room.value.leaderIndex === null
      )
        return null;
      return players[room.value.leaderIndex]?.id || null;
    });

    const currentLeaderName = computed(() => {
      if (!room.value || !currentLeaderId.value) return "未知";
      const leader = room.value.players.find(
        (p) => p.id === currentLeaderId.value
      );
      return leader?.name || "未知";
    });

    const requiredTeamSize = computed(() => {
      if (!room.value) return 0;
      const config = getPlayerCountConfig(room.value.players?.length || 5);
      if (!config) return 0;
      return config.quests[room.value.currentQuest || 0] || 0;
    });

    const isInTeam = computed(() => {
      if (!room.value) return false;
      // 优先使用 room 中的 currentPlayerId
      const currentPlayerId = room.value.currentPlayerId || socket.value?.id;
      if (!currentPlayerId) return false;
      return room.value.selectedTeam?.includes(currentPlayerId) || false;
    });

    const isAssassin = computed(() => {
      if (!room.value || !roleInfo.value) return false;
      return roleInfo.value.role === "刺客";
    });

    function initSocket() {
      // 确保 socket 连接
      if (!socket.value) {
        connect();
      } else if (!socket.value.connected) {
        // 如果 socket 存在但未连接，等待连接
        socket.value.once("connect", () => {
          setupSocketListeners();
        });
      }

      // 如果 socket 已连接，立即设置监听器
      if (socket.value && socket.value.connected) {
        setupSocketListeners();
      } else if (socket.value) {
        // 否则等待连接
        socket.value.once("connect", () => {
          setupSocketListeners();
        });
      }
    }

    function setupSocketListeners() {
      if (!socket.value) return;

      socket.value.on("roomUpdated", (updatedRoom) => {
        room.value = updatedRoom;
        if (updatedRoom.phase === "selectLeader") {
          selectedTeam.value = [];
        }
        // 如果队长已经选择了队伍，同步到本地
        if (updatedRoom.phase === "selectTeam" && updatedRoom.selectedTeam) {
          selectedTeam.value = [...updatedRoom.selectedTeam];
        }
      });

      socket.value.on("teamSelected", (data) => {
        success.value = "队伍选择成功，已自动发起投票";
        setTimeout(() => (success.value = ""), 3000);
      });

      socket.value.on("voteStarted", (data) => {
        success.value = `${data.leader} 发起了投票，请所有玩家投票`;
        setTimeout(() => (success.value = ""), 3000);
      });

      socket.value.on("gameStarted", (data) => {
        room.value = data.room;
        roleInfo.value = data.roleInfo;
      });

      socket.value.on("teamVoteResult", (data) => {
        // 保存投票结果详情
        teamVoteResult.value = {
          approved: data.approved,
          approveCount: data.approveCount,
          rejectCount: data.rejectCount,
          voteDetails: data.voteDetails || [],
        };

        // 系统自动判定结果
        if (data.approved) {
          // 小队成立，进入任务投票阶段
          success.value = `✅ 队伍投票通过！(${data.approveCount}票同意，${data.rejectCount}票拒绝) → 小队成立，进入任务投票阶段`;
        } else {
          // 队伍投票被拒绝，队长顺延
          error.value = `❌ 队伍投票被拒绝！(${data.approveCount}票同意，${data.rejectCount}票拒绝) → 队长顺延，继续游戏`;
          if (data.voteRound && data.voteRound >= 5) {
            error.value = "❌ 任务失败！连续5轮投票均被拒绝，坏人获胜！";
          }
        }
        setTimeout(() => {
          success.value = "";
          error.value = "";
        }, 4000);

        // 5秒后清除投票结果统计
        setTimeout(() => {
          teamVoteResult.value = null;
        }, 5000);
      });

      socket.value.on("leaderChanged", (data) => {
        success.value = data.message || "队长已更换，请等待新队长选择队伍";
        setTimeout(() => {
          success.value = "";
        }, 3000);
      });

      socket.value.on("questVoteStarted", (data) => {
        success.value = data.message || "小队成立！进入任务投票阶段！";
        setTimeout(() => (success.value = ""), 3000);
      });

      socket.value.on("launchVoteResult", (data) => {
        // 保存投票结果详情
        launchVoteResult.value = {
          launched: data.launched,
          launchCount: data.launchCount,
          notLaunchCount: data.notLaunchCount,
          voteDetails: data.voteDetails || [],
        };

        if (data.launched) {
          success.value = `发车投票通过！(${data.launchCount}票发车，${data.notLaunchCount}票不发车)，进入任务执行阶段`;
        } else {
          error.value = `发车投票失败！(${data.launchCount}票发车，${data.notLaunchCount}票不发车)，队长更换`;
          if (room.value && room.value.voteRound >= 5) {
            error.value = "任务失败！5轮投票均失败";
          }
        }
        setTimeout(() => {
          success.value = "";
          error.value = "";
        }, 3000);

        // 5秒后清除投票结果统计
        setTimeout(() => {
          launchVoteResult.value = null;
        }, 5000);
      });

      socket.value.on("questResult", (data) => {
        lastQuestResult.value = data.success;
        lastQuestFailCount.value = data.failCount;

        // 保存任务投票结果详情
        questVoteResult.value = {
          success: data.success,
          successCount: data.successCount || 0,
          failCount: data.failCount,
          questIndex: data.questIndex,
          voteDetails: data.voteDetails || [],
        };

        if (data.success) {
          success.value = `任务${data.questIndex + 1}成功！`;
        } else {
          error.value = `任务${data.questIndex + 1}失败！（${
            data.failCount
          }票失败）`;
        }
        setTimeout(() => {
          success.value = "";
          error.value = "";
          lastQuestResult.value = null;
        }, 5000);

        // 10秒后清除投票结果统计
        setTimeout(() => {
          questVoteResult.value = null;
        }, 10000);
      });

      socket.value.on("assassinationPhase", (data) => {
        success.value = "好人完成了3次任务！进入刺杀阶段！";
        selectedAssassinationTarget.value = null;
        setTimeout(() => (success.value = ""), 5000);
      });

      socket.value.on("assassinationResult", (data) => {
        if (data.isCorrect) {
          error.value = `刺客猜对了！刺杀了梅林（${data.merlinName}），坏人获胜！`;
        } else {
          success.value = `刺客猜错了！刺杀了${data.targetPlayerName}，但梅林是${data.merlinName}，好人获胜！`;
        }
        setTimeout(() => {
          success.value = "";
          error.value = "";
        }, 10000);
      });

      socket.value.on("gameFinished", (data) => {
        gameFinished.value = {
          winner: data.winner, // 'good' 或 'evil'
          players: data.players || [],
          questResults: data.questResults || [],
          successCount: data.successCount || 0,
          failCount: data.failCount || 0,
          assassination: data.assassination || null,
        };
        console.log("🎮 游戏结束", gameFinished.value);
      });

      socket.value.on("gameReset", (data) => {
        // 游戏已重置，清除游戏结束状态，返回房间
        gameFinished.value = null;
        success.value = data.message || "游戏已重置，可以开始新一局游戏";
        setTimeout(() => {
          success.value = "";
          // 返回房间页面
          router.push({ name: "room" });
        }, 2000);
      });

      socket.value.on("error", (message) => {
        error.value = message;
        setTimeout(() => (error.value = ""), 5000);
      });

      socket.value.on("roomInfo", (data) => {
        room.value = data.room;
        if (data.roleInfo) {
          roleInfo.value = data.roleInfo;
        }
      });

      // 如果从路由state获取初始数据
      if (history.state?.room && history.state?.roleInfo) {
        room.value = history.state.room;
        roleInfo.value = history.state.roleInfo;
      } else {
        // 否则请求房间信息（如果已在房间中）
        if (socket.value && socket.value.connected) {
          // 可以从localStorage或其他地方获取roomId
          const roomId = localStorage.getItem("currentRoomId");
          if (roomId) {
            socket.value.emit("getRoom", { roomId });
          }
        }
      }
    }

    function togglePlayerSelection(playerId) {
      if (!isCurrentLeader.value) return;
      const index = selectedTeam.value.indexOf(playerId);
      if (index > -1) {
        selectedTeam.value.splice(index, 1);
      } else {
        if (selectedTeam.value.length < requiredTeamSize.value) {
          selectedTeam.value.push(playerId);
        }
      }
    }

    function openTeamSelectModal() {
      showTeamSelectModal.value = true;
    }

    function closeTeamSelectModal() {
      showTeamSelectModal.value = false;
    }

    function handleConfirmTeam() {
      console.log("🔍 [handleConfirmTeam] 按钮被点击", {
        selectedTeamLength: selectedTeam.value.length,
        requiredTeamSize: requiredTeamSize.value,
        phase: room.value?.phase,
      });
      confirmTeamSelection();
    }

    function confirmAndCloseModal() {
      if (selectedTeam.value.length === requiredTeamSize.value) {
        // 确认队伍并自动发起投票
        confirmTeamSelection();
        closeTeamSelectModal();
      } else {
      }
    }

    function confirmTeamSelection() {
      if (!room.value) {
        error.value = "房间信息不存在";
        setTimeout(() => (error.value = ""), 3000);
        return;
      }

      if (!isCurrentLeader.value) {
        error.value = "您不是当前队长，无法确认队伍";
        setTimeout(() => (error.value = ""), 3000);
        return;
      }

      if (selectedTeam.value.length !== requiredTeamSize.value) {
        error.value = `队伍人数不正确，需要 ${requiredTeamSize.value} 人，当前 ${selectedTeam.value.length} 人`;
        setTimeout(() => (error.value = ""), 3000);
        return;
      }

      if (!socket.value || !socket.value.connected) {
        error.value = "Socket 未连接，无法发送请求";
        setTimeout(() => (error.value = ""), 3000);
        return;
      }

      socket.value.emit("selectTeam", {
        roomId: room.value.id,
        team: selectedTeam.value,
      });
    }

    function launchTeamVote() {
      if (!room.value || !isCurrentLeader.value) return;
      if (room.value.selectedTeam?.length !== requiredTeamSize.value) return;
      socket.value.emit("launchTeamVote", {
        roomId: room.value.id,
      });
    }

    function voteTeam(approve) {
      if (!room.value) return;
      socket.value.emit("voteForTeam", {
        roomId: room.value.id,
        approve,
      });
    }

    function voteLaunch(launch) {
      if (!room.value || !isInTeam.value) return;
      socket.value.emit("voteForLaunch", {
        roomId: room.value.id,
        launch,
      });
    }

    function voteQuest(success) {
      if (!room.value || !isInTeam.value) return;
      socket.value.emit("voteForQuest", {
        roomId: room.value.id,
        success,
      });
    }

    function selectAssassinationTarget(playerId) {
      if (!isAssassin.value) return;
      selectedAssassinationTarget.value = playerId;
    }

    function confirmAssassination() {
      if (
        !room.value ||
        !isAssassin.value ||
        !selectedAssassinationTarget.value
      )
        return;
      socket.value.emit("assassinate", {
        roomId: room.value.id,
        targetPlayerId: selectedAssassinationTarget.value,
      });
    }

    function getPlayerName(playerId) {
      if (!room.value) return "未知";
      const player = room.value.players.find((p) => p.id === playerId);
      return player?.name || "未知";
    }

    function getPlayerNumber(playerId) {
      if (!room.value) return "?";
      const index = room.value.players.findIndex((p) => p.id === playerId);
      return index !== -1 ? index + 1 : "?";
    }

    function getRoleClass(role) {
      if (!role) return "";
      if (["莫德雷德", "刺客", "爪牙"].includes(role)) return "evil";
      return "good";
    }

    function isGoodRole(role) {
      if (!role) return false;
      const goodRoles = ["梅林", "派西维尔", "忠臣"];
      return goodRoles.includes(role);
    }

    function backToRoom() {
      router.push({ name: "room" });
    }

    function backToHome() {
      // 返回首页
      router.push({ name: "home" });
    }

    function startNewGame() {
      if (!room.value || !isHost.value) {
        error.value = "只有房主可以开始新游戏";
        setTimeout(() => (error.value = ""), 3000);
        return;
      }

      // 发送重置游戏请求
      socket.value.emit("resetGame", {
        roomId: room.value.id,
      });
    }

    onMounted(() => {
      // 确保 socket 连接
      if (!socket.value) {
        connect();
      } else if (!socket.value.connected) {
        // 如果 socket 存在但未连接，等待连接
        socket.value.once("connect", () => {
          console.log("✅ Socket 已连接，ID:", socket.value.id);
          setupSocketListeners();
          requestRoomInfo();
        });
      }

      // 请求房间信息
      const requestRoomInfo = () => {
        const roomId = localStorage.getItem("currentRoomId");
        if (roomId && socket.value && socket.value.connected) {
          console.log("📡 请求房间信息，roomId:", roomId);
          socket.value.emit("getRoom", { roomId });
        }
      };

      // 等待 socket 连接后再设置监听器
      const setupAfterConnect = () => {
        if (socket.value && socket.value.connected && socket.value.id) {
          console.log("✅ Socket 已连接，ID:", socket.value.id);
          setupSocketListeners();
          requestRoomInfo();
        } else {
          // 如果还没连接，等待连接
          if (socket.value) {
            socket.value.once("connect", () => {
              console.log("✅ Socket 已连接，ID:", socket.value.id);
              setupSocketListeners();
              requestRoomInfo();
            });
          } else {
            // 如果 socket 不存在，等待一下再试
            setTimeout(setupAfterConnect, 100);
          }
        }
      };

      // 立即尝试设置
      setupAfterConnect();

      // 如果还没连接，等待一下再试
      if (!socket.value || !socket.value.connected) {
        setTimeout(setupAfterConnect, 300);
        setTimeout(setupAfterConnect, 800);
      } else if (socket.value.connected) {
        // 如果已经连接，立即设置
        setupSocketListeners();
        requestRoomInfo();
      }
    });

    onUnmounted(() => {
      // 不断开全局 socket，因为可能其他组件还在使用
      // 如果需要完全断开，可以在退出应用时手动调用 disconnect()
    });

    return {
      socket,
      room,
      roleInfo,
      selectedTeam,
      error,
      success,
      lastQuestResult,
      lastQuestFailCount,
      teamVoteResult,
      launchVoteResult,
      questVoteResult,
      isCurrentLeader,
      currentLeaderId,
      currentLeaderName,
      requiredTeamSize,
      isInTeam,
      togglePlayerSelection,
      handleConfirmTeam,
      confirmTeamSelection,
      launchTeamVote,
      openTeamSelectModal,
      closeTeamSelectModal,
      confirmAndCloseModal,
      showTeamSelectModal,
      voteTeam,
      voteLaunch,
      voteQuest,
      getPlayerName,
      getPlayerNumber,
      getRoleInfo,
      getRoleClass,
      isGoodRole,
      backToRoom,
      backToHome,
      startNewGame,
      gameFinished,
      isHost,
      isAssassin,
      selectedAssassinationTarget,
      selectAssassinationTarget,
      confirmAssassination,
    };
  },
};
</script>

